# -*- coding:utf-8 -*-
import traceback

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.pool import QueuePool

# from model.database_entity import ModelInfo
from util.config_reader import read_database_config
from util.loguru_util import myLogger


def get_db():
    # pass
    myLogger.info("get db session")
    db = SessionLocal().session
    try:
        yield db
        db.commit()
    except Exception as e:
        db.rollback()
        myLogger.error("database error: ")
        myLogger.error(traceback.format_exc())
    finally:
        db.close()
        myLogger.info("close db session")


def get_engine():
    mysql_config = read_database_config()
    db_driver = str(mysql_config['driver'])
    max_connections = int(mysql_config['max_connection'])
    host = str(mysql_config['host'])
    port = int(mysql_config['port'])
    user = str(mysql_config['user'])
    password = str(mysql_config['password'])
    database = str(mysql_config['db_name'])
    pool_size = int(mysql_config['pool_size'])
    # charset = mysql_config['charset']
    echo = mysql_config['echo']
    url = f"{db_driver}://{user}:{password}@{host}:{port}/{database}"

    engine = create_engine(url=url, poolclass=QueuePool, pool_size=pool_size, max_overflow=max_connections,
                           echo=echo)
    return engine


class SessionLocal:
    def __init__(self):
        engine = get_engine()
        self.session = scoped_session(
            sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=True))


if __name__ == "__main__":
    db = SessionLocal().session
    # res1 = db.query(ModelInfo).all()

    # model1 = ModelInfo(
    #     model_name="model2",
    #     model_version="1.2.0",
    #     pod_name="model2:1.2.0-pod",
    #     create_time=datetime.now()
    # )
    # db.add(model1)
    # db.commit()
    # res2 = db.query(ModelInfo).filter_by(model_name='model2').first()
    # res2.model_name = "model3"
    # db.commit()
    #
    # res1 = db.query(ModelInfo).all()
    # res3 = db.query(ModelInfo).filter(ModelInfo.model_name == 'model2').all()
    # # res2.model_name = "model3"
    # # db.close()
    # # print 放到前面会报错 'ModelInfo' object has no attribute '_sa_instance_state'
    # print('res1', res1)
    #
    # print('res3:', res3)
